import {
	loadingType
} from "./dict"

export function isWeixinClient() {
	var ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		return true
	} else {
		return false
	}
}

export function isAndroid() {
	let ua = navigator.userAgent;
	return ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
}

export function getRect(selector, all, context) {
	return new Promise(function(resolve) {
		let qurey = uni.createSelectorQuery();

		if (context) {
			qurey = uni.createSelectorQuery().in(context);
		}

		qurey[all ? 'selectAll' : 'select'](selector).boundingClientRect(function(rect) {
			if (all && Array.isArray(rect) && rect.length) {
				resolve(rect);
			}
			if (!all && rect) {
				resolve(rect);
			}
		}).exec();
	});
}

export function listToTree(list, tree, parentId) {
	list.forEach(item => {
		// 判断是否为父级菜单
		if (item.parentId === parentId) {
			const child = {
				...item,
				key: item.id || item.name,
				children: []
			}
			// 迭代 list， 找到当前菜单相符合的所有子菜单
			listToTree(list, child.children, item.id)
			// 删掉不存在 children 值的属性
			if (child.children.length <= 0) {
				delete child.children
			}
			// 加入到树中
			tree.push(child)
		}
	})
}

export async function queryListPageFunc(fun, page, size, params, dataList = [], status, offset = '0') {
	dataList = Object.assign([], dataList)
	if (status == loadingType.FINISHED) return false
	const res = await fun({
		offset: offset === '0' ? (page-1) * size : offset,
		limit: size,
		...params
	})
	const { code, data, err_no } = res.data
	if (code === 200 || err_no === 0) {
		let list = data
		dataList.push(...list)
		if (list.length < size) {
			status = loadingType.FINISHED
		}
		if (dataList.length <= 0) {
			status = loadingType.EMPTY
		}
		page = ++page
	} else {
		status = loadingType.ERROR
	}
	return {
		page,
		dataList,
		status
	}
}

export function toast(info = {}, navigateOpt) {
	let title = info.title || ''
	let icon = info.icon || 'none'
	let endtime = info.endtime || 2000
	if (title) uni.showToast({
		title: title,
		icon: icon,
		duration: endtime
	})
	if (navigateOpt != undefined) {
		if (typeof navigateOpt == 'object') {
			let tab = navigateOpt.tab || 1,
				url = navigateOpt.url || '';
			switch (tab) {
				case 1:
					setTimeout(function() {
						uni.switchTab({
							url: url
						})
					}, endtime);
					break;
				case 2:
					setTimeout(function() {
						uni.navigateTo({
							url: url,
						})
					}, endtime);
					break;
				case 3:
					setTimeout(function() {
						uni.navigateBack({
							delta: parseInt(url),
						})
					}, endtime);
					break;
				case 4:
					setTimeout(function() {
						uni.reLaunch({
							url: url,
						})
					}, endtime);
					break;
				case 5:
					setTimeout(function() {
						uni.redirectTo({
							url: url,
						})
					}, endtime);
					break;
			}
		} else if (typeof navigateOpt == 'function') {
			setTimeout(function() {
				navigateOpt && navigateOpt();
			}, endtime);
		}
	}
}

export function paramsToStr(params) {
	let p = '';
	if (typeof params == 'object') {
		p = '?'
		for (let props in params) {
			p += `${props}=${params[props]}&`
		}
		p = p.slice(0, -1)
	}
	return p
}

export function currentPage() {
	let pages = getCurrentPages();
	let currentPage = pages[pages.length - 1];
	return currentPage || {};
}

export function timeago(dateTimeStamp){  
     var minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
     var hour = minute * 60;
     var day = hour * 24;
     var week = day * 7;
     var halfamonth = day * 15;
     var month = day * 30;
     var now = new Date().getTime();   //获取当前时间毫秒
     var diffValue = now - dateTimeStamp;//时间差
     if(diffValue < 0){
         return;
     }
     var minC = diffValue/minute;  //计算时间差的分，时，天，周，月
     var hourC = diffValue/hour;
     var dayC = diffValue/day;
     var weekC = diffValue/week;
     var monthC = diffValue/month;
	 let result = '';
     if(monthC >= 1 && monthC <= 12){
         result = " " + parseInt(monthC) + "月前"
     }else if(weekC >= 1 && weekC <= 3){
         result = " " + parseInt(weekC) + "周前"
     }else if(dayC >= 1 && dayC <= 6){
         result = " " + parseInt(dayC) + "天前"
     }else if(hourC >= 1 && hourC <= 24){
         result = " " + parseInt(hourC) + "小时前"
     }else if(minC >= 1 && minC <= 59){
         result =" " + parseInt(minC) + "分钟前"
     }else if(diffValue >= 0 && diffValue <= minute){
         result = "刚刚"
     }else {
         var datetime = new Date();
         datetime.setTime(dateTimeStamp);
         var Nyear = datetime.getFullYear();
         var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
         var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
         var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
         var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
         var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
         result = Nyear + "-" + Nmonth + "-" + Ndate
     }
     return result;
 }
